package com.ldx.tvolatile;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lidexin
 * @create 2021-10-18 22:57
 */
//不保证原子性
public class VDemo02 {
    //volatile不保证原子性
//    private   volatile static int num = 0;
    private   volatile static AtomicInteger num = new AtomicInteger();
    public static void add() {//sychronized加上为20000，保证原子性
//        num++;
        num.getAndIncrement();//AtomicInteger + 1
    }

    public static void main(String[] args) {
        //理论上num结果应该为20000
        for (int i = 1; i <=20 ; i++) {
            new Thread(()->{
                for(int j= 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }

        while (Thread.activeCount() > 2) { //main gc
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + "" + num);
    }
}
